<template>
   <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
         <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
         <el-breadcrumb-item>商城管理</el-breadcrumb-item>
         <el-breadcrumb-item :to="{ path: '/shop/products' }">商品列表</el-breadcrumb-item>
         <el-breadcrumb-item>新增商品</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="hengxian"></div>

      <el-form :model="product" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
               v-loading="loading">
         <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="first">
               <el-form-item label="所属分类" prop="category_id">
                  <el-cascader placeholder="请选择分类" size="mini" :options="categories"
                               @change="handleSelectChange(category)"
                               :props="props" v-model="category" filterable>
                  </el-cascader>
               </el-form-item>
               <el-form-item label="商品名称" prop="name">
                  <el-input size="mini" v-model="product.name" placeholder="请输入商品名称"></el-input>
               </el-form-item>
               <el-form-item label="商品单价" prop="price">
                  <el-input size="mini" type="number" v-model="product.price" placeholder="请输入商品单价"></el-input>
               </el-form-item>
               <el-form-item label="商品库存" prop="stock">
                  <el-input size="mini" v-model="product.stock" placeholder="请输入商品库存"></el-input>
               </el-form-item>
               <el-form-item label="缩略图" prop="image">
                  <el-upload class="avatar-uploader" action="/photos" :show-file-list="false"
                             :on-success="handleAvatarSuccess"
                             :before-upload="beforeAvatarUpload">
                     <img v-if="product.image" :src="product.image" class="avatar">
                     <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
               </el-form-item>
               <el-form-item label="描述信息" prop="description">
                  <el-input type="textarea" v-model="product.description" :rows="3"></el-input>
               </el-form-item>
               <el-form-item label="是否上架" prop="is_onsale">
                  <el-radio-group v-model="product.is_onsale">
                     <el-radio :label="1">是</el-radio>
                     <el-radio :label="0">否</el-radio>
                  </el-radio-group>
               </el-form-item>
               <el-form-item label="推荐类型" prop="check">
                  <template>
                     <el-checkbox-group v-model="check" size="mini" @change="handleChangeStatus(check)">
                        <el-checkbox-button v-for="item in status" :label="item.val" :key="item.val">{{item.name}}
                        </el-checkbox-button>
                     </el-checkbox-group>
                  </template>
               </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品介绍" name="second">

               <vue-ueditor-wrap v-model="product.content" :config="myConfig"></vue-ueditor-wrap>

            </el-tab-pane>
            <el-tab-pane label="商品相册" name="third">
               <el-form-item label="商品相册" prop="product_id">
                  <el-upload class="upload-demo" action="/photos" drag multiple :limit="limit"
                             :on-success="handleSuccess"
                             :on-exceed="handleLimit"
                             :file-list="fileList"
                             :show-file-list="false">
                     <i class="el-icon-upload"></i>
                     <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                     <span slot="tip" class="el-upload__tip"> 只能上传jpg/png/gif文件，且不超过2M</span>
                  </el-upload>

                  <!--拖动排序-->
                  <draggable tag="div" :list="fileList" @update="dataDragEnd" handle=".avatar">
                     <div v-for="(item,index) in fileList" :label="item" :value="index" :key="index" class="paixu">
                        <img v-if="item.response" :src="item.response.msg" alt="" class="avatar"
                             title="拖动排序">
                        <div class="view watch" @click="handlePictureCardPreview(item)"><i class="el-icon-zoom-in"></i>
                        </div>
                        <div class="view delete" @click="handleRemove(index,item,fileList)"><i
                           class="el-icon-close"></i>
                        </div>
                     </div>
                  </draggable>
                  <!--查看大图-->
                  <el-dialog :visible.sync="dialogVisible" :width="width" custom-class="an-img-dialog" :center="true">
                     <img :src="product.product_id" alt="" @load="onLoad">
                  </el-dialog>

               </el-form-item>
            </el-tab-pane>
         </el-tabs>

         <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')" size="mini">立即创建</el-button>
            <el-button @click="resetForm('ruleForm')" size="mini">重置</el-button>
         </el-form-item>
      </el-form>
   </div>
</template>

<script>
   import draggable from 'vuedraggable';
   import VueUeditorWrap from 'vue-ueditor-wrap' // ES6 Module

   export default {
      name: "Create",
      components: {
         draggable,
         VueUeditorWrap
      },
      data() {
         return {
            myConfig: {
               // 编辑器不自动被内容撑高
               autoHeightEnabled: false,
               // 初始容器高度
               initialFrameHeight: 600,
               // 初始容器宽度
               initialFrameWidth: '100%',
               serverUrl: '/vendor/UEditor/php/controller.php',
               // UEditor 资源文件的存放路径
               UEDITOR_HOME_URL: '/vendor/UEditor/'
            },
            activeName: 'first',
            loading: false,
            dialogVisible: false,
            width:'',
            fileList: [],
            limit: 25,  //限制上传张数
            categories: [],
            category: '',
            props: {
               expandTrigger: 'hover',
               value: 'id',
               label: 'name',
            },
            status: [
               {name: '置顶', val: 'is_top'},
               {name: '热销', val: 'is_hot'},
               {name: '推荐', val: 'is_recommend'},
               {name: '新品', val: 'is_new'}
            ],
            check: [],
            product: {
               category_id: '',
               name: '',
               price: '',
               stock: 99,
               image: '',
               description: '',
               is_onsale: 1,
               is_top: 0,
               is_hot: 0,
               is_recommend: 0,
               is_new: 0,
               content: '',
               product_id: [],
            },
            rules: {
               //    category_id: [
               //       {required: true, message: '请选择分类', trigger: 'change'}
               //    ],
               //    name: [
               //       {required: true, message: '请输入商品名称', trigger: 'change'}
               //    ],
               //    price: [
               //       {required: true, message: '请输入商品价格', trigger: 'change'}
               //    ],
               //    image: [
               //       {required: true, message: '请上传封面', trigger: 'change'}
               //    ],
               //    description: [
               //       {required: true, message: '请输入商品描述', trigger: 'change'},
               //    ],
               //    product_id: [
               //       {required: true, message: '请上传商品图片', trigger: 'change'}
               //    ],
            }
         };
      },
      created() {
         this.init();
      },
      methods: {
         onLoad(e){
            const img = e.target;
            let width = 0;
            if (img.fileSize > 0 || (img.width > 1 && img.height > 1)) {
               width = img.width + 40;
            }
            this.width = width + 'px';
         },
         //推荐类型
         handleChangeStatus(val) {
            this.check = val;
            for (let i = 0; i < this.check.length; i++) {
               this.product[this.check[i]] = 1;
            }
         },
         //选择分类
         handleSelectChange(val) {
            // console.log(val[1]);
            this.product.category_id = val[1];
         },
         //初始化
         init() {
            this.loading = true;
            //所有分类
            axios.get(`/admin/shop/categories`)
               .then((res) => {
                  this.categories = res.data;
                  this.loading = false;
               });
         },
         //图片上传
         handleAvatarSuccess(res, file) {
            this.product.image = res.msg;
         },
         beforeAvatarUpload(file) {
            const arr = ['image/jpeg', 'image/png', 'image/gif'];
            // const isJPG = file.type === 'image/jpeg';
            const isJPG = arr.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
               this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
            }
            if (!isLt2M) {
               this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
         },
         //多图上传
         handleRemove(index, file, fileList) {
            this.fileList.splice(index, 1);
            this.product.product_id = fileList.map((res) => {
               return {image: res.response.msg, sort: res.index};
            });
            // console.log(this.product.product_id);
         },
         handlePictureCardPreview(file) {
            // console.log(file);
            this.product.product_id = file.response.msg;
            this.dialogVisible = true;
         },
         //超出限制个数
         handleLimit(file, fileList) {
            if (fileList.length >= this.limit || fileList.length == 0) {
               this.$message.error('最多上传' + this.limit + '张图片');
            } else {
               this.$message.error('还剩' + (this.limit - fileList.length) + '张图片');
            }
         },
         handleSuccess(response, file, fileList) {
            this.fileList = fileList;
            // for (let i = 0; i < this.fileList.length; i++) {
            //    fileList[i].index = i;
            // }
            this.product.product_id = this.fileList.map((res) => {
               if (res.response) {
                  // return {image: res.response.msg, sort: res.index};  //方法（1）
                  return {image: res.response.msg, sort: this.fileList.indexOf(res)};  //方法（2）
               }
            });
            // console.log(this.product.product_id);
         },
         //拖动排序
         dataDragEnd(evt) {
            const fileList = this.fileList;
            // for (let i = 0; i < fileList.length; i++) {
            //    fileList[i].index = i;
            // }
            this.product.product_id = fileList.map((item) => {
               // return {image: item.response.msg, sort: item.index};   //方法（1）
               return {image: item.response.msg, sort: fileList.indexOf(item)};   //方法（2）
            });
            // console.log(this.product.product_id);
         },
         //表单提交
         submitForm(formName) {
            this.$refs[formName].validate((valid) => {
               if (valid) {
                  // console.log(this.product);
                  axios.post(`/admin/shop/products`, this.product)
                     .then((res) => {
                        if (res.data.status == 1) {
                           this.$message({
                              showClose: true,
                              message: res.data.msg,
                              type: 'success'
                           });
                           this.$router.push('/shop/products');
                           this.$refs[formName].resetFields();   //重置表单
                        } else {
                           this.$message.error(res.data.msg);
                        }
                     })
               } else {
                  console.log('error submit!!');
                  return false;
               }
            });
         },
         resetForm(formName) {
            this.$refs[formName].resetFields();
         },

      }
   }
</script>

<style>
   .demo-ruleForm {
      width: 65%;
      margin: 0 auto;
   }

   .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
   }

   .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
   }

   .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
   }

   .avatar {
      width: 178px;
      height: 178px;
      display: block;
   }

   .el-upload__tip {
      color: red;
   }

   .paixu {
      display: inline-block;
      margin: 5px;
      cursor: Move;
   }

   .paixu {
      position: relative;
   }

   .paixu .view {
      position: absolute;
      top: 0;
      width: 19px;
      height: 19px;
      line-height: 19px;
      text-align: center;
      background-color: red;
      color: #fff;
      cursor: pointer;
   }

   .paixu .watch {
      left: 0;
   }

   .paixu .delete {
      right: 0;
   }
</style>